import { log } from './log';


// @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
const sdAPI = window.SDWebUI_ImageQuickSend
const config = await sdAPI.getConfig();

export class SettingListeners {
    document: Element
    constructor(doc: Element) {//传入一个document对象
        this.document = doc
    }

    async serverStatusTextListener() {
        const serverStatus_text = this.document.querySelector('#serverStatus') as HTMLElement;
        serverStatus_text.innerText = await sdAPI.getServerStatus();
    }

    async isActiveSwitchListener() {
        const isActive_switch = this.document.querySelector('#isActive') as HTMLInputElement
        isActive_switch.classList.toggle('is-active', config.isActive);
        isActive_switch.addEventListener('click', async (_event: any) => {
            const newValue = isActive_switch.classList.toggle('is-active')
            await sdAPI.setConfig({
                isActive: newValue
            })
        });
    }

    async portInuptListener() {
        const port_input = this.document.querySelector('#port') as HTMLInputElement
        port_input.value = config?.port?.toString() || '配置信息读取失败';

        port_input.addEventListener('change', async () => {
            const value = Number(port_input.value)

            if (isNaN(value) || value < 5000 || value > 20000) {
                port_input.value = '6020' // 自动纠正显示
                await sdAPI.setConfig({ port: 6020 })
                log('端口范围错误，已经重置为默认端口')
                return
            }

            await sdAPI.setConfig({ port: value })
        });
    }

    async groupListInuptListener() {
        // 群组设置
        const groupList_input = this.document.querySelector('#groupList') as HTMLInputElement
        // 完整处理流程示例
        groupList_input.value = ((config?.groupList || '配置信息读取失败') as Array<unknown>)
            .filter(item => item != null)  // 过滤 null/undefined
            .map(item => String(item).trim())
            .filter(Boolean)
            .join(',');

        groupList_input.addEventListener('change', async (event: any) => {
            await sdAPI.setConfig({
                groupList: event.target.value
                    .split(',')
                    .map((item: string) => item.trim()) // 先去除首尾空格
                    .filter((item: string) => item !== '') // 过滤空字符串
                    .map(String) // 转为字符串
                    .filter((num: number) => !isNaN(num)) // 可选：过滤掉 NaN（非数字字符）
            })
        });
    }

    async timeOutInuptListener() {
        // 时间设置
        const timeOut_input = this.document.querySelector('#timeOut') as HTMLInputElement
        // 完整处理流程示例
        timeOut_input.value = config?.timeOut.toString() || '配置信息读取失败';

        timeOut_input.addEventListener('change', async (_event: any) => {
            const value = Number(timeOut_input.value)

            if (isNaN(value) || value < 5 || value > 60) {
                timeOut_input.value = '5' // 自动纠正显示
                await sdAPI.setConfig({ timeOut: 5 })
                log('时间范围错误，已经重置为默认时间')
                return
            }

            await sdAPI.setConfig({
                timeOut: Number(timeOut_input.value)
            })
        });
    }

    async githubButtonListener() {
        const github_button = this.document.querySelector('#github') as HTMLButtonElement
        github_button.addEventListener('click', () => {
            // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
            LiteLoader.api.openExternal('https://github.com/yalwolf/LiteLoaderQQNT-SDWebUI-ImageQuickSend');
        });
    }

    async onLoad() {
        this.serverStatusTextListener()
        this.isActiveSwitchListener()
        this.portInuptListener()
        this.groupListInuptListener()
        this.timeOutInuptListener()
        this.githubButtonListener()
    }
}